﻿using System.IO;
using System.Threading.Tasks;

namespace Fetches.Fetch.Utils.FileHosting
{
    public class LocalFileHosting : IHostFileProvider
    {
        private string _cachePath;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="config"></param>
        public void Initialize(string config)
        {
            var basePath = config;
            if (string.IsNullOrEmpty(basePath))
            {
                basePath = @"D:\Deploy\Hosting";
            }

            _cachePath = basePath;
            Directory.CreateDirectory(_cachePath);
            for (int i = 0; i < 256; i++)
            {
                var subPath = Path.Combine(_cachePath, i.ToString("X2"));
                Directory.CreateDirectory(subPath);
            }
        }

        public Task WriteAsync(string hash, byte[] data)
        {
            var file = GetFilePathFromHash(hash);

            return Task.Run(() =>
            {
                if (!File.Exists(file))
                {
                    Task.Run(() => { File.WriteAllBytes(file, data); });
                }
            });
        }

        public long ItemLength(string hash)
        {
            var filePath = GetFilePathFromHash(hash);
            var file = new FileInfo(filePath);
            return file.Length;
        }

        public Stream Read(string hash)
        {
            var filePath = GetFilePathFromHash(hash);
            if (!File.Exists(filePath))
            {
                return null;
            }
            return new FileStream(filePath, FileMode.Open, FileAccess.Read);
        }


        private string GetFilePathFromHash(string hash)
        {
            var dest = $@"{_cachePath}\{hash.Substring(0, 2)}\{hash.Substring(2)}";
            return dest;
        }

    }
}
